package com.mybatils.controller;

import com.alibaba.fastjson.JSONObject;
import com.mybatils.db1.mapper.TestMapper;
import com.mybatils.db2.mapper.Test2Mapper;
import exam.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/5/21 10:06
 * @since JDK 1.8
 */
@RestController
@Api(tags = {"mybatils多数据源测试"})
@RequestMapping("mybatils")
public class MybatisController {

    @Autowired
    private TestMapper test1Mapper;

    @Autowired
    private Test2Mapper test2Mapper;

    @Autowired
    DataSource dataSource;


    @GetMapping("test1")
    public JSONObject test1Controller(@RequestParam(value = "title",required = false)String title){
        List<Map<String, Object>> mapList=test1Mapper.selectMapObjectList(title);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("data",mapList);
        return jsonObject;
    }




    @GetMapping("db1")
    @ApiOperation("数据源连接1测试")
    public JSONObject db1ConnectionController(){
      List<Map<String, Object>> mapList=test1Mapper.stringMapObjectList();
      return Result.successObject(mapList);
    }

    @GetMapping("db2")
    @ApiOperation("数据源连接2测试")
    public JSONObject db2ConnectionController(){
        List<Map<String, Object>> objectMap=test2Mapper.stringDb2ObjectMapList();
        return Result.successObject(objectMap);
    }

    @GetMapping("db2create")
    @ApiOperation("db2建表")
    public JSONObject db2CreateTableController(){
        String sql= "CREATE TABLE `note`  (\n" +
                "  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键id',\n" +
                "  `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '笔记标题',\n" +
                "  `note` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '笔记备注',\n" +
                "  `typeid` int(10) NULL DEFAULT NULL COMMENT '笔记类型',\n" +
                "  `createtime` datetime NULL DEFAULT NULL COMMENT '创建时间',\n" +
                "  `updatetime` datetime NULL DEFAULT NULL COMMENT '更新时间',\n" +
                "  `version` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '版本号',\n" +
                "  `status` int(255) NULL DEFAULT NULL COMMENT '数据状态',\n" +
                "  PRIMARY KEY (`id`) USING BTREE\n" +
                ") ENGINE = InnoDB AUTO_INCREMENT = 46 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;\n" +
                "\n" ;
        System.out.println(sql);
       int code=test2Mapper.updateSql(sql);
        return Result.successObject("成功");
    }

    @GetMapping("selectListDb1Note")
    @ApiOperation("批量导入数据测试")
    public JSONObject db1ListSelectAllController(){
      List<Map<String, Object>> objectMapList=test1Mapper.selectNoteMapListObject();
      objectMapList.forEach(e->{
          System.out.println(e);
      });
      //String sql=inserSqlCreateOne(objectMapList.get(0),"note");
      saveListMap(objectMapList,"note","id");
      return Result.successObject(objectMapList);
    }

    public int saveListMap(List<Map<String, Object>> mapList,String table,String field){
        if(mapList==null){
            return 0;
        }
        for (int i = 0; i < mapList.size(); i++) {
            Object value=mapList.get(i).get(field);
            if(value==null){
                continue;
            }
            String valueString = String.valueOf(value);
            String selectSql=selectCreateOne(table,field,valueString);
            Object obj=test2Mapper.selectSql(selectSql);
            if(obj!=null){
                String updateSql=updateSqlCreate(table,mapList.get(i),field);
                System.out.println(updateSql);
                continue;
            }
            String sql=inserSqlCreateOne(mapList.get(i),table);
            test2Mapper.insertSql(sql);
        }
        return 1;
    }

    public String selectCreateOne(String table,String field,String value){
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("select * from ");
        stringBuffer.append(table);
        stringBuffer.append(" where ").append(field).append(" ='").append(value)
                .append("'");
        return stringBuffer.toString();
    }



    public String inserSqlCreateOne(Map<String, Object> objectMap,String tableName){
            if(objectMap==null) {
                return null;
            }
            //生成INSERT INTO table(field1,field2) 部分
            StringJoiner sbField = new StringJoiner(",","(",")");
            //生成VALUES('value1','value2') 部分
            StringJoiner sbValue = new StringJoiner(",","(",")");
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append("INSERT INTO ").append(tableName.toLowerCase());
            for(Map.Entry<String, Object> entry : objectMap.entrySet()){
                String mapKey = entry.getKey();
                String mapValue =String.valueOf( entry.getValue());
                sbField.add("`" + mapKey + "`");
                sbValue.add("'" + mapValue + "'");
            }
            return stringBuffer.append(sbField.toString()).append(" VALUES ").append(sbValue.toString()).toString();
    }


    /**
     *
     * @param tableName 表名
     * @param dataMap  要更改的数据
     * @param field   更据哪一个属性的值来修改
     * @return
     */
    public  String updateSqlCreate(String tableName, Map<String, Object> dataMap,String field) {
        if(dataMap==null || ! dataMap.containsKey(field)) {
            return null;
        }
        String idValue =String.valueOf(dataMap.get(field)) ;
        StringBuffer sb = new StringBuffer();
        StringJoiner stringJoiner=new StringJoiner(",");
        sb.append("UPDATE "+ tableName.toLowerCase() +" SET ");
        for(Map.Entry<String, Object> entry : dataMap.entrySet()){
            if(entry.getValue()==null){
                continue;
            }
            String mapKey = entry.getKey();
            String mapValue = String.valueOf(entry.getValue());
            if(entry.getKey().toLowerCase().equals(field)) {
                continue;
            }
            stringJoiner.add("`" + mapKey + "`='" + mapValue + "' ");
        }
        sb.append(stringJoiner.toString()).append( " where ").append(field)
                .append(" =").append("'").append(idValue).append("'");
        return  sb.toString();
    }







}
